package com.fmistuff.threadedcalc;

import java.math.BigInteger;

import com.fmistuff.threadedcalc.ui.ILoggable;

public class Calculator {

	/**
	 * @param args
	 */
	public static BigInteger calculate(String expr, int numberOfThreads,
			ILoggable log) {
		BigInteger result = null;
		try {

			int cnt = 1;
			long start = System.currentTimeMillis();

			for (int j = 0; j < cnt; j++) {
				ExpressionTree tree = new ExpressionTree(expr);
				ThreadPool pool = new ThreadPool(numberOfThreads);
				Thread poolThread = new Thread(pool);
				Thread mainThread = pool.Initialize(tree.rootNode);
				poolThread.start();
				mainThread.join();
				poolThread.interrupt();
				result = pool.evaluatedNodes.get(tree.rootNode).result;

			}
			long end = System.currentTimeMillis();
			log.log("Time " + (end - start) / cnt + "ms " + numberOfThreads
					+ " threads.");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

}
